package cc.lj1.auth.helper;

import cc.lj1.auth.services.AuthUserService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.Map;

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static<T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static<T> T getBean(String name, Class<T> tClass) {
        if(StringUtils.hasLength(name))
            return applicationContext.getBean(name, tClass);
        else {
            String[] beanNames = applicationContext.getBeanNamesForType(tClass);
            for(String beanName : beanNames) {
                try {
                    // 用于解决Service中使用了@Transactional等注解之后
                    // 原始Service被cglib代理，导致无法获取到原始Class及相关的Annotation的问题
                    T bean = AopTargetUtils.getTarget(applicationContext.getBean(beanName, tClass));
                    Service service = bean.getClass().getAnnotation(Service.class);
                    if (service != null && !StringUtils.hasLength(service.value()))
                        return bean;
                    Component component = bean.getClass().getAnnotation(Component.class);
                    if (component != null && !StringUtils.hasLength(component.value()))
                        return bean;
                }
                catch (Exception e) {
                }
            }
            return null;
        }
    }
}
